package dryven.init;

import java.util.Collection;

import dryven.discovery.DiscoveryConsumer;
import dryven.model.di.DependencyInjector;
import dryven.persistence.PersistenceDependencyInjectingBinder;
import dryven.persistence.PersistenceInitializer;
import dryven.persistence.provider.PersistenceProvider;
import dryven.request.RequestLifeCycleListener;

public abstract class PersistenceFrontControllerFactory extends
		DependencyInjectingFrontControllerFactory {

	private PersistenceProvider persistenceProvider;
	

	@Override
	protected void addRequestLifeCycleListeners(
			Collection<RequestLifeCycleListener> listeners) {
		super.addRequestLifeCycleListeners(listeners);
		listeners.add(new PersistenceInitializer(getPersistenceProvider(),getApplicationConfiguration()));
		
	}
	
	@Override
	protected void addDependencyInjectors(Collection<DependencyInjector> dis) {
		dis.add(new PersistenceDependencyInjectingBinder(getApplicationConfiguration()));
	}
	
	protected abstract PersistenceProvider createPersistenceProvider();

	protected PersistenceProvider getPersistenceProvider() {
		if(persistenceProvider==null) {
			persistenceProvider = createPersistenceProvider();
			//if the provider needs discovery, add his listener
			if(persistenceProvider instanceof DiscoveryConsumer) {
				addDiscoveryListener(((DiscoveryConsumer)persistenceProvider).getDiscoveryListener());
			}
		}
		return persistenceProvider;
	}
}
